package com.smsc.headend.connector.utils;

import cn.hutool.core.util.HexUtil;
import com.smsc.headend.module.protocol.cosem.util.ByteUtils;
import gurux.dlms.GXByteBuffer;
import gurux.dlms.enums.Command;
import gurux.dlms.internal.GXCommon;

import java.nio.charset.StandardCharsets;

public class PacketAddressUtil {

    public static String getMeterAddress(byte[] packets) {
        String hexResult = HexUtil.decodeHexStr(ByteUtils.byteToHexString(packets).replace(" ", ""));
        if (hexResult.contains("DHB;")) {
            // Nesco GPRS 表 心跳报文
            return hexResult.substring(hexResult.lastIndexOf("DHB;") + 4);
        } else if (hexResult.contains("DRLI;")) {
            // Nesco GPRS 表 登录报文
            return hexResult.substring(hexResult.lastIndexOf("DRLI;") + 5);
        }
        GXByteBuffer byteBuffer = new GXByteBuffer(packets);
        if (byteBuffer.getUInt8() == 0x7E) {
            byteBuffer.position(3);
            GXCommon.getHDLCAddress(byteBuffer); //targetAddress 不要删除 position有变化
            int sourceAddress = GXCommon.getHDLCAddress(byteBuffer);
            return String.valueOf(sourceAddress);
        } else {
            byteBuffer.position(0);
            // DCU相关的地址信息
            Short tag = byteBuffer.getUInt8(8);
            if (tag == Command.GATEWAY_RESPONSE || tag == Command.GATEWAY_REQUEST) {
                Integer deviceAddressLength = byteBuffer.getUInt16(9);
                return byteBuffer.getString(11, deviceAddressLength);
            }
        }
        return null;
    }

    /**
     * packet(44 52 4C 49 3B 38 39 38 36 30 34 34 39 31 38 31 39 43 30 34 32 30 32 30 34)
     * 获取wasion登陆帧电表的sim卡号信息
     * @param packets
     * @return
     */
    public static String getHbPacketByDrliPacket(byte[] packets) {
        String hexResult = HexUtil.decodeHexStr(ByteUtils.byteToHexString(packets).replace(" ", ""));
        if (hexResult.contains("DRLI;")) {
            // Nesco GPRS 表 登录报文
            hexResult = hexResult.substring(hexResult.lastIndexOf("DRLI;") + 5);
            return ByteUtils.byteToHexString(("DHB;"+hexResult).getBytes(StandardCharsets.UTF_8));
        }
        return null;
    }
}
